import Taro, { Component } from "@tarojs/taro";
import { View, Text, Picker } from "@tarojs/components";
import { connect } from "@tarojs/redux";
import { fileRequest, $Req } from "@utils";
import { AtForm, AtInput, AtButton } from "taro-ui";
import "./index.scss";

@connect(
  ({ userModel }) => ({
    userModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
  })
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: "身份认证",
  };

  constructor(props) {
    super(...arguments);
    this.state = {
      identitycardName: null,
      identitycardNo: null,
      identitycardZm: null,
      identitycardFm: null,
      identitycardZmUrl: null,
      identitycardFmUrl: null,
      identitycardTime: null,
      // 用户认证状态
      identitycardStatus: null,
    };
  }

  onItemClick() {}

  componentDidMount() {
    this.getUserIdentityInfo();
  }

  async uploadImg(imgUrl, type) {
    let { code, message, data } = await fileRequest({
      type: "post",
      url: "/file/uploadFile",
      data: imgUrl,
    });
    data = JSON.parse(data);
    
    if (data.code == 200) {
      Taro.showToast({
        title: data.message
      })
      if (type == 1) {
        this.setState({
          identitycardZmUrl: data.data,
        })
      } else {
        this.setState({
          identitycardFmUrl: data.data,
        })
      }

    } else {
      Taro.showToast({
        title: data.message,
        icon: "none"
      })
    }

  }

  onSelectImg(type) {
    Taro.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        console.log(res);
        let value = res && res.tempFilePaths[0];
        if (type) {
          this.uploadImg(value, 1);
          this.setState({
            identitycardZm: value,
          });
        } else {
          this.uploadImg(value, 0);
          this.setState({
            identitycardFm: value,
          });
        }
      },
    });
  }

  // 获取认证信息
  async getUserIdentityInfo() {
    let {
      userModel: { userInfo },
      userAction,
    } = this.props;
    let { code, message, data } = await $Req({
      type: "get",
      url: "/indexUser/getAuthenticate",
      data: {},
    });

    this.setState({
      identitycardStatus: data.status,
      identitycardZm: data.imgUrl,
      identitycardFm: data.negativeImgUrl,
      identitycardZmUrl: data.imgUrl,
      identitycardFmUrl: data.negativeImgUrl,
      identitycardName: data.fullName,
      identitycardNo: data.identificationNo,
    });
  }

  // 用户认证接口
  async setUserIdentityInfo() {
    let {
      userModel: { userInfo },
      userAction,
    } = this.props;

    const {
      identitycardName,
      identitycardNo,
      identitycardZmUrl,
      identitycardFmUrl,
      identitycardStatus
    } = this.state;

    if (!identitycardName) {
      Taro.showToast({
        title: "姓名不能为空",
        icon: "none"
      })

      return false;
    }

    if (!identitycardNo) {
      Taro.showToast({
        title: "身份证号不能为空",
        icon: "none"
      })

      return false;
    }

    if (isNaN(identitycardNo)) {
      Taro.showToast({
        title: "身份证号码错误",
        icon: "none"
      })

      return false;
    }

    if (identitycardNo && identitycardNo.length != 18) {
      Taro.showToast({
        title: "身份证号码错误",
        icon: "none"
      })
      return false;
    }

    let postDatas = {
      userId: userInfo.userId,
      fullName: identitycardName,
      identificationNo: identitycardNo,
      imgUrl: identitycardZmUrl,
      negativeImgUrl: identitycardFmUrl, 
    };

    identitycardStatus == 2 || !identitycardStatus ? postDatas.status = 0 : identitycardStatus;

    let { code, message, data } = await $Req({
      type: "post",
      url: "/indexUser/addAuthenticate",
      data: postDatas,
    });
    
    if (code !== 200) return;
    Taro.showToast({
      title: "提交成功!",
      icon: "none",
      mask: true,
    });
    
    Taro.navigateBack({
      delta: 1,
    });
  }

  render() {
    return (
      <View className="at-row page-identity-index">
        <View className="at-col c0">
          <View className="at-row">
            <View className="at-col">
              <View style={{ textAlign: "center", lineHeight: "50px", color: "#fff", backgroundColor: (this.state.identitycardStatus == 1 || this.state.identitycardStatus == 0 ? "#27B5F2" : "#FF7933") }}>
                {
                  this.state.identitycardStatus == 1 ?
                  <View>认证成功</View>
                  :
                  null
                }

                {
                  this.state.identitycardStatus == 0 ?
                  <View>提交成功等待审核</View>
                  :
                  null
                }

                {
                  this.state.identitycardStatus == 2 ?
                  <View>审核失败，不是有效的身份证信息</View>
                  :
                  null
                }
              </View>
              <AtForm>
                <AtInput
                  name="name"
                  title="姓名："
                  type="text"
                  placeholder="请填写姓名"
                  value={this.state.identitycardName}
                  onChange={(v) => {
                    this.state.identitycardName = v;
                  }}
                  disabled={this.state.identitycardStatus == 1 || this.state.identitycardStatus == 0 ? true : false}
                ></AtInput>

                <AtInput
                  name="idcard"
                  title="身份证号:"
                  type="number"
                  maxLength={18}
                  placeholder="请填写身份证号"
                  value={this.state.identitycardNo}
                  onChange={(v) => {
                    this.setState({
                      identitycardNo: v
                    })
                  }}
                  disabled={this.state.identitycardStatus == 1 || this.state.identitycardStatus == 0 ? true : false}
                />
              </AtForm>
            </View>
          </View>
          <View className="at-row" style="margin-top:10PX;background: #fff;">
            <View className="at-col" style="padding: 15PX;padding-bottom:0;">
              <Text>身份证正面</Text>
            </View>
          </View>
          <View className="at-row" style="background: #fff;">
            <View
              className="at-col"
              style="padding: 15PX;padding-top:10PX;"
              onClick={() => {
                this.state.identitycardStatus == 1 || this.state.identitycardStatus == 0 ? null :  this.onSelectImg(1);
              }}
            >
              <image
                style="width:100%;height:210PX;"
                src={
                  this.state.identitycardZm ||
                  "https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com" + "/shopping/user/id_face.png"
                }
              />
            </View>
          </View>

          <View className="at-row" style="background: #fff;">
            <View className="at-col" style="padding: 15PX;padding-bottom:0;">
              <Text>身份证背面</Text>
            </View>
          </View>
          <View className="at-row" style="background: #fff;">
            <View
              className="at-col"
              style="padding: 15PX;padding-top:10PX;"
              onClick={() => {
                this.state.identitycardStatus == 1 || this.state.identitycardStatus == 0 ? null :  this.onSelectImg(0);
              }}
            >
              <image
                style="width:100%;height:210PX;"
                src={
                  this.state.identitycardFm ||
                  "https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com" + "/shopping/user/id_back.png"
                }
              />
            </View>
          </View>

          {this.state.identitycardStatus == 1 || this.state.identitycardStatus == 0 ? null : (
            <View
              className="at-row at-row__justify--center at-row__align--center"
              style="background: #fff;"
            >
              <View className="at-col btn-col" style="padding: 15PX;">
                <AtButton
                  circle
                  type="primary"
                  className="btn-submit"
                  onClick={() => {
                    this.setUserIdentityInfo();
                  }}
                >
                  提交
                </AtButton>
              </View>
            </View>
          )}
        </View>
      </View>
    );
  }
}
